<?php

namespace app\admin\model\xilujob;

use fast\Tree;
use think\Cache;
use think\Model;


class JobCategory extends Model
{

    

    

    // 表名
    protected $name = 'xilujob_job_category';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        //'labour_job_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
        self::afterWrite(function ($row){
            self::clearCache();
        });
        self::afterDelete(function ($row){
            self::clearCache();
        });
    }
    protected static function clearCache(){
        $cacheKey = \app\common\model\xilujob\JobCategory::CACHE_KEY;
        Cache::rm($cacheKey);
    }

    
    public function getLabourJobList()
    {
        return ['0' => __('Labour_job 0'), '1' => __('Labour_job 1')];
    }


    public function getLabourJobTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['labour_job']) ? $data['labour_job'] : '');
        $list = $this->getLabourJobList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 获取数组格式列表数据
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getCategoryList() {
        //use cache
        //$list = Cache::get('job_category_collection');
        //if(!$list) {
            $list = collection(static::order('weigh', 'desc')->order('id', 'asc')->select())->toArray();
        //    Cache::set('job_category_collection', $list);
       // }

        return $list;
    }

    /**
     * 获取格式化后的分类列表
     * @return array
     */
    public static function getCategoryData() {
        $tree = new Tree();
        $tree->init(static::getCategoryList());
        $categoryList = $tree->getTreeList($tree->getTreeArray(0), 'category_name');
        $categoryData = [];
        foreach ($categoryList as $k => &$v) {
            $categoryData[$v['id']] = $v['category_name'];
        }
        return $categoryData;
    }

    /*
    * @return Tree
    */
    public static function getCategoryTree() {
        $tree = new Tree();
        $tree->init(static::getCategoryList());
        return $tree;
    }


    public function getNamePathAttr($value,$data){
        if(!$value) return  '';
        $value = $data['pid'] == 0 ? str_replace($data['category_name'].',','',$value): str_replace(','.$data['category_name'].',','',$value);
        return str_replace(',','--',$value);
    }

}
